package com.relytosoft.mizar.media.camera.services.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.relytosoft.dubhe.common.core.base.page.PageQuery;
import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.core.utils.BeanCopyUtils;
import com.relytosoft.mizar.media.camera.api.entity.CameraBase;
import com.relytosoft.mizar.media.camera.api.entity.CameraChannel;
import com.relytosoft.mizar.media.camera.api.entity.CameraPlatform;
import com.relytosoft.mizar.media.camera.api.pojo.dto.CameraChannelDto;
import com.relytosoft.mizar.media.camera.api.pojo.vo.CameraChannelVo;
import com.relytosoft.mizar.media.camera.services.mapper.CameraChannelMapper;
import com.relytosoft.mizar.media.camera.services.service.CameraBaseService;
import com.relytosoft.mizar.media.camera.services.service.CameraChannelService;
import com.relytosoft.mizar.media.camera.services.service.CameraPlatformService;
import com.relytosoft.mizar.media.camera.services.utils.FeignInResultHandleUtils;
import com.relytosoft.mizar.media.camera.services.utils.FeignInSystemUtils;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import com.relytosoft.mizar.media.common.utils.AesUtils;
import com.relytosoft.mizar.media.system.api.feign.SystemFeignInService;
import com.relytosoft.mizar.media.system.api.pojo.dto.DistrictFeignDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author a3621
 */
@Service
public class CameraChannelServiceImpl extends ServiceImpl<CameraChannelMapper, CameraChannel> implements CameraChannelService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private CameraPlatformService cameraPlatformService;

    @Resource
    private CameraBaseService cameraBaseService;

    @Resource
    private SystemFeignInService systemFeignInService;

    @Override
    public void channelPage(Integer type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "SELECT_HK_CHANNEL");
        jsonObject.put("Data", type == 0 ? "false" : "true");
        MqttOp.publish(MediaMqConstants.CAMERA_TOPIC, JSON.toJSONString(jsonObject));
    }

    @Override
    public IPage<CameraChannelVo> selectChannelPageList(PageQuery pageQuery, CameraChannelDto cameraChannelDto) {
        CameraChannelVo cameraChannelVo = BeanCopyUtils.copy(cameraChannelDto, CameraChannelVo.class);
        if (StrUtil.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        //获取分页信息
        Page<CameraChannelVo> page = pageQuery.build();
        Integer districtId = cameraChannelVo.getDistrictId();
        List<Integer> cameraIds = new ArrayList<>();
        List<DistrictFeignDto> allArea = FeignInResultHandleUtils.handlerResponse(systemFeignInService.selectDistrictList());
        IPage<CameraChannelVo> iPage;
        if (districtId != null && allArea != null && allArea.size() > 0) {
            //查询本区域及下级子节点
            List<Integer> areaIds = FeignInSystemUtils.findAreaAllChildren(districtId, cameraIds, allArea);
            //查询所有区域关联的设备并获取设备id集合
            List<CameraBase> cameraBaseList = cameraBaseService.list(new QueryWrapper<CameraBase>().lambda().in(areaIds.size() > 0, CameraBase::getDistrictId, areaIds));
            cameraIds = cameraBaseList.stream().map(CameraBase::getId).collect(Collectors.toList());
            //根据设备查询区域下的所有通道
            if (cameraIds.size() > 0) {
                iPage = this.baseMapper.selectChannelPageList(page, cameraChannelVo, cameraIds);
            } else {
                return page;
            }
        } else {
            //直接查询所有通道信息
            iPage = this.baseMapper.selectChannelPageList(page, cameraChannelVo, cameraIds);
        }
        //设置区域信息
        for (CameraChannelVo channelVo : iPage.getRecords()) {
            channelVo.setDistrictName(FeignInSystemUtils.completeRoute(channelVo.getDistrictId(), allArea));
        }
        //判断是否去重
        if (cameraChannelVo.getList() != null && cameraChannelVo.getList().size() > 0) {
            List<CameraChannelVo> records = iPage.getRecords();
            records = records.stream().filter(item -> !cameraChannelVo.getList().contains(item.getId())).collect(Collectors.toList());
            iPage.setRecords(records);
        }
        return iPage;
    }

    @Override
    public void setChannelCode(List<CameraChannel> cameraChannelList) {
        List<Integer> list = cameraChannelList.stream().map(CameraChannel::getId).collect(Collectors.toList());
        if (list.size() > 0) {
            List<CameraPlatform> cameraPlatformList =
                    cameraPlatformService.list(new QueryWrapper<CameraPlatform>().lambda().in(CameraPlatform::getOwnId, list));
            for (CameraChannel cameraChannel : cameraChannelList) {
                for (CameraPlatform platform : cameraPlatformList) {
                    if (cameraChannel.getId().equals(platform.getOwnId())) {
                        cameraChannel.setPlatformChannelCode(platform.getPlatformChannelCode());
                    }
                }
            }
        }
    }

    @Override
    public CameraChannelVo byId(Integer id) {
        List<DistrictFeignDto> allArea = FeignInResultHandleUtils.handlerResponse(systemFeignInService.selectDistrictList());
        CameraChannelVo channelVo = this.baseMapper.byId(id);
        if (channelVo == null) {
            throw new ServiceException("该数据不存在");
        }
        if (channelVo.getDistrictId() != null) {
            channelVo.setDistrictName(FeignInSystemUtils.completeRoute(channelVo.getDistrictId(), allArea));
        }
        return channelVo;
    }

    @Override
    public boolean updateCameraChannel(CameraChannel cameraChannel) {
        return this.updateById(cameraChannel);
    }

    @Override
    public String getRtspTemplate(Integer cameraId, String template) {
        CameraBase cameraBase = cameraBaseService.getById(cameraId);
        if (cameraBase == null) {
            throw new ServiceException("该设备不存在");
        }
        if (StrUtil.isEmptyIfStr(cameraBase.getPassword())) {
            throw new ServiceException("该设备无密码");
        }
        String userName = cameraBase.getUserName();
        String password = cameraBase.getPassword();
        String ip = cameraBase.getIp();
        if (!StrUtil.isEmptyIfStr(userName)) {
            userName = AesUtils.aesDeCode(userName);
            template = template.replace("账号", userName);
        }
        if (!StrUtil.isEmptyIfStr(password)) {
            password = AesUtils.aesDeCode(password);
            template = template.replace("密码", password);
            template = template.replace("ip", ip);
            template = template.replace("端口", "554");
        }
        log.info("rtsp地址为:{}", template);
        return AesUtils.aesEnCode(template);
    }
}
